package demo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SensitiveInfoProcessor {

    public static void process(Object obj) throws IllegalAccessException, InvocationTargetException {
        if (obj == null) {
            return;
        }
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(SensitiveInfo.class)) {
                SensitiveType type = field.getAnnotation(SensitiveInfo.class).value();
                field.setAccessible(true);
                String value = (String) field.get(obj);
                if (value != null && !value.isEmpty()) {
                    field.set(obj, desensitize(type, value));
                }
            }
        }
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(SensitiveInfo.class)) {
                SensitiveType type = method.getAnnotation(SensitiveInfo.class).value();
                if (method.getParameterTypes().length > 0) {
                    continue;
                }
                method.setAccessible(true);
                Object value = method.invoke(obj);
                if (value instanceof String && !((String) value).isEmpty()) {
                    method.invoke(obj, desensitize(type, (String) value));
                }
            }
        }
    }

    private static String desensitize(SensitiveType type, String value) {
        // 根据不同的敏感信息类型进行脱敏处理
        switch (type) {
            case MOBILE:
                return value.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            case ID_CARD:
                return value.replaceAll("(\\d{6})\\d{8}(\\d{4})", "$1********$2");
            default:
                return value;
        }
    }
}


